import 'dart:convert';

import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import 'package:badges/badges.dart';

// import 'comp_prod_item.dart';
import '../../blocs/cart.dart';
import '../../blocs/product.dart';

class ProductListScreen extends StatefulWidget {
  final String param;
  ProductListScreen(this.param, {Key? key}) : super(key: key);
  _ProductListScreenState createState() => _ProductListScreenState();
}

class _ProductListScreenState extends State<ProductListScreen> {
  late Offset cartOffset;

  late ProductBloc listSourceRepository;

  GlobalKey cartKey = GlobalKey();
  GlobalKey rootKey = GlobalKey();

  late Map im_param;

  @override
  void initState() {
    super.initState();
    im_param = jsonDecode(widget.param);
    listSourceRepository = new ProductBloc();
    listSourceRepository.criteria = {
      "category_id": im_param['category_id'],
      "keyword": im_param['keyword'],
    };
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      RenderBox renderBox = cartKey.currentContext?.findRenderObject() as RenderBox;
      cartOffset = renderBox.localToGlobal(Offset.zero);
      AppSession.prodListCart = cartOffset;
    });
    AppSession.prodListRoot = rootKey;
  }

  @override
  void dispose() {
    listSourceRepository.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var lv_title;
    if ((im_param['category_name'] ?? '').isNotEmpty)
      lv_title = im_param['category_name'];
    if ((im_param['keyword'] ?? '').isNotEmpty) lv_title = im_param['keyword'];
    return Material(
      color: Colors.white,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            brightness: Brightness.light,
            title: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                Navigator.pop(context);
              },
              child: Container(
                padding: EdgeInsets.only(right: 15.w),
                child: Row(
                  children: <Widget>[
                    Icon(
                      Icons.chevron_left,
                      color: AppColor.blackMain,
                      size: 32,
                    ),
                    Text(' ${lv_title}',
                        style: TextStyle(color: AppColor.blackMain)),
                  ],
                ),
              ),
            ),
            automaticallyImplyLeading: false,
            // backgroundColor: Colors.white,
            pinned: true,
            actions: <Widget>[
              Container(
                key: rootKey,
                // child: Column(
                //   children: <Widget>[
                //     // HomeCartBlock(iv_key: test),
                //     Container(),
                //     Container(
                margin: EdgeInsets.only(right: 37.w),
                // padding: EdgeInsets.all(0.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      child: Consumer<CartBloc>(
                        builder: (context, _cart, child) => Builder(
                          builder: (context) {
                            return GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                if (_cart.amount == 0)
                                  AppPopupService.showAlertSimple(
                                      'I', '购物车是空的', '请先选择商品加入购物车，然后再结账哦');
                                else
                                  App.router
                                      .navigateTo(context, AppRoutes.orderCart);
                              },
                              child: Badge(
                                badgeColor: Colors.red,
                                toAnimate: true,
                                shape: BadgeShape.circle,
                                // borderRadius: 20,
                                borderRadius: BorderRadius.circular(20),
                                animationType: BadgeAnimationType.scale,
                                child: Image.asset(
                                  'assets/order/cart_circle.png',
                                  key: cartKey,
                                ),
                                badgeContent: Text(_cart.amount.toString(),
                                    style: TextStyle(color: Colors.white)),
                              ),
                            );
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          // Container(
          //   child: Column(
          //     children: <Widget>[
          //       Row(
          //         children: <Widget>[],
          //       ),
          //       Row(
          //         children: <Widget>[],
          //       )
          //     ],
          //   ),
          // ),

          LoadingMoreSliverList(
            SliverListConfig<Map>(
              itemBuilder: _ProductListScreenState.generateItem,
              sourceList: listSourceRepository,
//                    showGlowLeading: false,
//                    showGlowTrailing: false,
              padding: EdgeInsets.all(0.0),
              // collectGarbage: (List<int> indexes) {
              //   ///collectGarbage
              //   indexes.forEach((index) {
              //     final item = listSourceRepository[index];
              //   });
              // },
              // viewportBuilder: (int firstIndex, int lastIndex) {
              //   // print("viewport : [$firstIndex,$lastIndex]");
              // },
            ),
          ),

          // generateItem(1, 'https://www.tudouapp.ca/app/testimg/prod1.png', 'A菜', '\$ 1.99/包', {
          //   "sku_id": "",
          // }),
          // generateItem(2, 'https://www.tudouapp.ca/app/testimg/prod2.png', 'A菜', '\$ 1.99/包', {
          //   "sku_id": "",
          // }),
          // generateItem(
          //   'assets/test/prod1.png',
          //   'A菜',
          //   '\$ 1.99/包',
          // ),
        ],
      ),
    );
  }

  // Widget _categoryComp(int iv_category_id, String iv_category_name){
  //   var lv_img = 'img_cate_'+iv_category.toString()+'.png';
  //   return Container(
  //     height: (70*3).h,
  //     width: (56 * 3).w,
  //     child: Column(
  //        children: <Widget>[
  //          Image.asset(lv_img),
  //         Text(iv_category_name, style: TextStyle(color: ),
  //        ],
  //     ),
  //   );
  // }

  static Widget generateItem(BuildContext context, Map item, int index) {
    late Offset temp;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        App.router.navigateTo(
            context, AppRoutes.productDetail + '?prod_id=${item['sku_id']}');
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 22.w, vertical: 5.w),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: 120.w,
              height: 150.h,
              padding: EdgeInsets.symmetric(
                horizontal: 5.w,
                vertical: 5.h,
              ),
              child: CachedNetworkImage(
                imageUrl: item['image_url'],
                fit: BoxFit.cover,
              ),
            ),
            Container(
              width: 211.w,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                // crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 211.w,
                    height: 101.h,
                    padding: EdgeInsets.only(left: 10.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          item['sku_name'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: AppColor.nameProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 15.sp,
                          ),
                        ),
                        Text(
                          item['sku_desc'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: AppColor.descProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 11.sp,
                          ),
                        ),
                        item['outstock_info'] == 1
                            ? Container(
                                width: 80.w,
                                padding: EdgeInsets.symmetric(horizontal: 5.w),
                                height: 16.h,
                                decoration: BoxDecoration(
                                  color: Color(0xffFDE3E3),
                                  borderRadius: BorderRadius.circular(2),
                                ),
                                child: Center(
                                    child: Text('库存不足',
                                        style: TextStyle(
                                          color: Color(0xffFF3434),
                                          fontSize: 10.sp,
                                        ))))
                            : Container(),
                        Text(
                          '\$ ' + item['sku_price'] + ' / ' + item['unit_desc'],
                          softWrap: true,
                          maxLines: 1,
                          overflow: TextOverflow.fade,
                          style: TextStyle(
                            color: AppColor.priceProduct,
                            fontWeight: FontWeight.normal,
                            fontSize: 15.sp,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(right: 10.w),
                    height: 50.h,
                    child: Consumer<CartBloc>(
                      builder: (context, _cart, child) => Builder(
                        builder: (context) {
                          return Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              GestureDetector(
                                onTap: () {
                                  _cart.reduceItem(item['sku_id']);
                                },
                                child: Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 10.w),
                                  child: Icon(
                                    // MaterialCommunityIcons.minus_circle_outline,
                                    LineIcons.minusCircle,
                                    color: AppColor.nameProduct,
                                    size: 28,
                                  ),
                                ),
                              ),
                              Container(
                                width: 30.w,
                                alignment: Alignment.center,
                                child: Text(
                                  _cart.itemAmount(item['sku_id']).toString(),
                                  style: TextStyle(
                                    color: AppColor.priceProduct,
                                    fontWeight: FontWeight.normal,
                                    fontSize: 20.sp,
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onPanDown: (details) {
                                  temp = new Offset(details.globalPosition.dx,
                                      details.globalPosition.dy);
                                },
                                onTap: () {
                                  late Function callback;
                                  // setState(() {
                                  _cart.addItem(item);
                                  OverlayEntry entry =
                                      OverlayEntry(builder: (ctx) {
                                    return ParabolaAnimateWidget(
                                      AppSession.prodListRoot,
                                      temp,
                                      AppSession.prodListCart,
                                      Icon(
                                        Icons.add_circle,
                                        color: Colors.redAccent,
                                      ),
                                      callback,
                                      duration: 800,
                                    );
                                  });

                                  callback = (status) {
                                    if (status == AnimationStatus.completed) {
                                      entry.remove();
                                    }
                                  };

                                  Overlay.of(AppSession.prodListRoot.currentContext!)!.insert(entry);
                                },
                                child: Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 10.w),
                                  child: Icon(
                                    // MaterialCommunityIcons.plus_circle,
                                    LineIcons.plusCircle,
                                    color: AppColor.nameProduct,
                                    size: 28,
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
